package com.example.problem3;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

@Slf4j
@SpringBootApplication
public class Problem3Application implements ApplicationRunner {

	public static void main(String[] args) {
		SpringApplication.run(Problem3Application.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {

		log.info("URL普通接口调用--------------------");
		urlCall();
	}

	public void urlCall() throws IOException {
		String url ="http://localhost:8080/demoController/resultJson";
		URL wsUrl = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setConnectTimeout(5*1000);
		conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
		conn.setRequestProperty("Content-Length", "length");
		OutputStream os = conn.getOutputStream();
		InputStream is = conn.getInputStream();
		byte[] b = new byte[1024];
		int len = 0;
		String s = "";
		while((len = is.read(b)) != -1){
			String ss = new String(b,0,len,"UTF-8");
			s += ss;
		}
		is.close();
		os.close();
		conn.disconnect();
		System.out.println("服务器返回数据:"+s);
	}
}
